export default class WebWorker {
    #filePath;
    #worker;
    #action;
    #onError;

    constructor(options) {
        this.#filePath = options.filePath || "";
        this.#action = Object.prototype.toString.call(options.action) === '[object Function]' ? options.action : ((data, args) => { console.log(data, args) });
        this.#onError = Object.prototype.toString.call(options.onError) === '[object Function]' ? options.onError : ((event) => {
            console.error([
                'ERROR: Line ', event.lineno, ' in ', event.filename, ': ', event.message
            ].join(''));
        });
    }

    createWorker() {
        if (this.#filePath) {
            this.#worker = new Worker(this.#filePath);
            this.#worker.onmessage = (event) => {
                const { data } = event;
                this.#action(data, event);
            };
            this.#worker.onerror = (event) => {
                this.#onError(event);
            };
            return this.#worker;
        } else {
            return false;
        }
    }

    postMessage(data) {
        this.#worker.postMessage(data);
    }

    closeWorker() {
        this.#worker.terminate();
    }
}